﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Principal;
using StructureMap;
using BonsaiScrum.Core.Persistance;

namespace BonsaiScrum.Mvc.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
    public sealed class RoleAttribute : AuthorizeFilterBase
    {
        public RoleAttribute(params Type[] roles)
        {
            Roles = roles;
        }

        public Type[] Roles { get; private set; }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (UserIsNotAuthenticated(httpContext.User)) return false;

            var userRepository = ObjectFactory.GetInstance<IUserReportingRepository>();
            var currentUserName = httpContext.User.Identity.Name;
            var currentUser = userRepository.GetUserWithUserName(currentUserName);

            return currentUser.IsAuthorizedForAny(Roles);
        }

        private bool UserIsNotAuthenticated(IPrincipal user)
        {
            return (user.Identity.IsAuthenticated == false);
        }
    }
}
